import datetime
import json
import os
import sys

import boto3
import requests

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from config import *

service_names = {
    'Amazon Athena': 'Athena',
    'Amazon ElastiCache': 'ElastiCache',
    'EC2 - Other': 'EC2其他费用',
    'Amazon Elastic Compute Cloud - Compute': 'EC2实例(包含EMR实例)',
    'Amazon Elastic File System': 'ElasticFileSystem',
    'Amazon Elastic MapReduce': 'EMR集群管理(不包含实例)',
    'Amazon Glue': 'Glue',
    'Amazon Key Management Service': 'KeyManagement',
    'Amazon Lambda': 'Lambda',
    'Amazon Redshift': 'Redshift',
    'Amazon Relational Database Service': 'RDS',
    'Amazon SageMaker': 'SageMaker',
    'Amazon Secrets Manager': 'SecretsManager',
    'Amazon Simple Notification Service': 'SNS',
    'Amazon Simple Storage Service': 'S3存储',
    'Amazon Step Functions': 'StepFunctions',
    'Amazon Virtual Private Cloud': 'PrivateCloud',
    'AmazonCloudWatch': 'CloudWatch',
    'Tax': 'Tax'
}


def run():
    today = datetime.datetime.today()+datetime.timedelta(hours=8)
    # 昨天
    yesterday = (today - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    client = boto3.client('ce',
                          aws_access_key_id=FORMAL_S3_CONFIG['access_key'],
                          aws_secret_access_key=FORMAL_S3_CONFIG['secret_key'],
                          region_name=FORMAL_S3_CONFIG['region_name'])

    resp = client.get_cost_and_usage(
        TimePeriod={
            'Start': f'{yesterday}',
            'End': f'''{today.strftime('%Y-%m-%d')}'''
        },
        Granularity='MONTHLY',
        Metrics=['UnblendedCost'],
        GroupBy=[
            {
                'Type': 'DIMENSION',
                'Key': 'SERVICE'
            },
            {
                'Type': 'DIMENSION',
                'Key': 'INSTANCE_TYPE'
            }
        ],
    )
    times = resp['ResultsByTime']
    rs = {}
    for day in times:
        start = day['TimePeriod']['Start']
        groups = day['Groups']
        for one in groups:
            if one['Keys'][0] in service_names:
                key = service_names[one['Keys'][0]]
            else:
                key = one['Keys'][0]
            if key in rs:
                li = rs[key]
            else:
                li = []
            if one['Keys'][1] == 'NoInstanceType':
                instance = '无实例费用'
            else:
                instance = one['Keys'][1]
            m = {'instance': instance, 'Amount': round(float(one['Metrics']['UnblendedCost']['Amount']), 0)}
            li.append(m)
            rs[key] = li
        total = 0
        for k in rs:
            v = rs[k]
            service_total = 0
            for ins in v:
                service_total += ins['Amount']
                total += ins['Amount']
            v.insert(0, {'instance': '总计', 'Amount': service_total})
        rs['total'] = [{'instance': '总计', 'Amount': total}]
        send(rs, start, 0)
        # print(rs)
    print(rs)


def send(map, date, c):
    qywx_robot_url = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=0c4a703b-fa8b-4348-a442-9c690a605c60"
    send_url = qywx_robot_url
    headers = {
        'Content-Type': 'application/json'
    }
    total = map['total'][0]['Amount']
    try:
        content = f'{date} AWS使用成本: <font color=\"warning\">{total}</font>'
        for k, li in map.items():
            if k != 'total':
                for ins in li:
                    amount = ins['Amount']
                    if amount > 0.0:
                        if ins['instance'] == '总计':
                            content = content + f"\n> {k}: {amount}"
                        else:
                            content = content + f"\n> <font color=\"comment\">   {ins['instance']}: </font> {amount}  "
        msg = {
            "msgtype": 'markdown',
            "markdown": {'content': content}
            }
    except Exception as e:
        print(str(e))
        msg = {
            "msgtype": 'text',
            "text": {'content': f'执行错误,{str(map)}'}
        }
    print(msg)
    response = requests.post(url=send_url, data=json.dumps(msg), headers=headers)
    print(map)
    print(response)
    print('已发送消息到企业微信')

# 空调mqtt数据超过阈值设备通知
if __name__ == '__main__':
    run()
